/***************************************************************************
                          kcontroldoc.cpp  -  description
                             -------------------
    begin                : Sat May 26 2001
    copyright            : (C) 2001 by Javier Campos
    email                : javi_cms@terra.es
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kcontroldoc.h"
#include "kcontroldoc.moc"

#include "kcontroladdedit.h"
#include "kcontrolheader.h"

#include <kstddirs.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kedittoolbar.h>
#include <kkeydialog.h>

#include <qlayout.h>
#include <qsplitter.h>
#include <qprinter.h>
#include <qpaintdevice.h>
#include <qpaintdevicemetrics.h>
#include <qfontmetrics.h>

static const char* const image0_data[] = {
"15 16 4 1",
"a c #0000ff",
"# c #008183",
"b c #c5c2c5",
". c #ffffff",
"...............",
".#############.",
".#...........#.",
".#...aaaa....#.",
".#..aa.baa...#.",
".#......aa...#.",
".#.....aab...#.",
".#....aab....#.",
".#....aab....#.",
".#.....b.....#.",
".#....aa.....#.",
".#....aa.....#.",
".#...........#.",
".#...........#.",
".#############.",
"..............."};

kcontroldoc::kcontroldoc(QWidget* parent, const char *name, WFlags f ) : KMainWindow(parent,name,f)
{
	KEDUCA = new FileRead();
	initMenuBar();
	init();
	configRead();
	this->setIcon( locate("appdata", "hicolor/16x16/actions/keducacontrol.png") );
	isOpenFile = false;
}

kcontroldoc::~kcontroldoc()
{
	delete KEDUCA;
}

/** Init graphical interface */
void kcontroldoc::init()
{
	QWidget *mainView = new QWidget(this, "mainview");

    QVBoxLayout *Form2Layout = new QVBoxLayout( mainView );
    Form2Layout->setSpacing( 2 );
    Form2Layout->setMargin( 0 );
	
		split = new QSplitter( mainView );
		split->setOrientation( QSplitter::Vertical );

    list_answer = new KListBox( split, "list_answer" );
    list_answer->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)7, (QSizePolicy::SizeType)7, list_answer->sizePolicy().hasHeightForWidth() ) );
//		connect( list_answer,  SIGNAL( executed(QListBoxItem *) ), this, SLOT( slotPreview(QListBoxItem *) ) );
		connect( list_answer,  SIGNAL( highlighted(QListBoxItem *) ), this, SLOT( slotPreview(QListBoxItem *) ) );

    preview = new QTextView( split, "preview" );
    preview->setFrameShape( QTextView::NoFrame );
    preview->setLineWidth( 1 );

    Form2Layout->addWidget( split );

	this->setCentralWidget( mainView );
}

/** Init menu bar settings */
void kcontroldoc::initMenuBar()
{
	KStdAction::openNew						(this, SLOT( slotFileOpenNew() ), actionCollection());
	KStdAction::open							(this, SLOT( slotFileOpen() ), actionCollection());
	recentFiles = KStdAction::openRecent(this, SLOT ( slotFileOpenURL(const KURL &)), actionCollection());
	KStdAction::save							(this, SLOT( slotFileSave() ), actionCollection());
	KStdAction::saveAs						(this, SLOT( slotFileSaveAs() ), actionCollection());
	KStdAction::print							(this, SLOT( slotFilePrint() ), actionCollection());
	(void)new KAction(i18n("Document Info"), "info", 0, this, SLOT( slotHeader() ), actionCollection(), "info_doc");
	KStdAction::close							(this, SLOT( close() ), actionCollection());	

	(void)new KAction(i18n("Add"), "addquestion", 0, this, SLOT( slotAdd() ), actionCollection(), "question_add");
	(void)new KAction(i18n("Edit"), "editquestion", 0, this, SLOT( slotEdit() ), actionCollection(), "question_edit");
	(void)new KAction(i18n("Remove"), "delquestion", 0, this, SLOT( slotRemove() ), actionCollection(), "question_remove");
	(void)new KAction(i18n("Up"), "up", 0, this, SLOT( slotUp() ), actionCollection(), "question_up");
	(void)new KAction(i18n("Down"), "down", 0, this, SLOT( slotDown() ), actionCollection(), "question_down");

	KStdAction::showToolbar				(this, SLOT( slotToggleToolBar()), actionCollection());
	KStdAction::keyBindings				(this, SLOT( slotConfigureKeys() ), actionCollection());
	KStdAction::configureToolbars	(this, SLOT( slotConfigureToolbar() ), actionCollection());

  createGUI( "keducacontrolui.rc" );
}

/** Delete current document and start new */
void kcontroldoc::slotFileOpenNew()
{
	if( KEDUCA ) delete KEDUCA;
	list_answer->clear();
	KEDUCA = new FileRead();	
	isOpenFile = false;
}

/** Open new document. */
void kcontroldoc::slotFileOpen()
{
  KURL url = KFileDialog::getOpenURL( QString::null, "*.edu|Educa "+i18n("file")+" (*.edu)", 0,  i18n("Open Educa file") );

  if( !url.isEmpty() )
     slotFileOpenURL( url );
}

/** Open new file */
void kcontroldoc::slotFileOpenURL( const KURL &url )
{
	QPixmap image0( ( const char** ) image0_data );
	delete KEDUCA;
	KEDUCA = new FileRead();
	if( !KEDUCA->openFile(url) ) { return; }
	recentFiles->addURL( url );
	list_answer->clear();
	isOpenFile = true;

	KEDUCA->recordFirst();
	while( !KEDUCA->recordEOF() )
	{
		list_answer->insertItem( image0, KEDUCA->getQuestion( FileRead::QF_text ) );
		KEDUCA->recordNext();
	}
}

/** Item select */
void kcontroldoc::slotPreview( QListBoxItem *item )
{
	bool match = false;
	QString tmp_listanswer;

	// FIND THE SELECT RECORD
	if( !item ) return;
	KEDUCA->recordFirst();
  while ( !KEDUCA->recordEOF() )
		{
		if( KEDUCA->getQuestion( FileRead::QF_text ) == item->text() ) { match = true; break; }
		KEDUCA->recordNext();
		}
	if( !match )	return;

	// START THE PREVIEW VALUES
	tmp_listanswer = "<p><b>" + i18n("Answers") + "</b></p><hr>";
	tmp_listanswer += "<p>";

	tmp_listanswer +="<TABLE>";
	KEDUCA->recordAnswerFirst();
	while( !KEDUCA->recordAnswerEOF() )
	{
		tmp_listanswer += "<TR><TD WIDTH=10 BGCOLOR=";
		KEDUCA->getAnswerValue() ? tmp_listanswer += "#006b6b>" : tmp_listanswer += "#b84747>";
		tmp_listanswer += "</TD><TD BGCOLOR=";
		KEDUCA->getAnswerValue() ? tmp_listanswer += "#daeaea>" : tmp_listanswer += "#eadada>";
		tmp_listanswer += KEDUCA->getAnswer( FileRead::AF_text );
		tmp_listanswer += "</TD></TR>";
		KEDUCA->recordAnswerNext();
	};
	tmp_listanswer += "</TABLE>";

	if( !KEDUCA->getQuestion( FileRead::QF_picture ).isEmpty() )
	{
	tmp_listanswer += "<table><tr><td><img src=";
	tmp_listanswer += KEDUCA->getQuestion( FileRead::QF_picture );
	tmp_listanswer += "></td>";
	tmp_listanswer += "<td align=right><b>" + i18n("Question Image") + "</b><hr>";
	tmp_listanswer += KURL(KEDUCA->getQuestion( FileRead::QF_picture )).fileName() + "</td></tr></table>";
	};

	if( KEDUCA->getQuestionInt( FileRead::QF_time ) > 0 )
	{
	tmp_listanswer += "<p><b>Time : </b>";
	tmp_listanswer += KEDUCA->getQuestion( FileRead::QF_time );
	tmp_listanswer += " seconds</p>";
	}	

	if( !KEDUCA->getQuestion( FileRead::QF_tip ).isEmpty() )
	{
	tmp_listanswer += "<p><b>Tip : </b>";
	tmp_listanswer += KEDUCA->getQuestion( FileRead::QF_tip );
	tmp_listanswer += "</p>";
	}	

	if( !KEDUCA->getQuestion( FileRead::QF_explain ).isEmpty() )
	{
	tmp_listanswer += "<p><b>Explain : </b>";
	tmp_listanswer += KEDUCA->getQuestion( FileRead::QF_explain );
	tmp_listanswer += "</p>";
	}	

	preview->setText( tmp_listanswer );
}

/** Read config data */
void kcontroldoc::configRead()
{
	KConfig *config = KGlobal::config();

	config->setGroup( "keducacontrol" );
	this->applyMainWindowSettings( config, "keducacontrol" );
	split->setSizes( config->readIntListEntry("Splitter_size") );
	recentFiles->loadEntries(config);
}

/** Write settings */
void kcontroldoc::configWrite()
{
	KConfig *config = KGlobal::config();

	config->setGroup( "keducacontrol" );
	this->saveMainWindowSettings( config, "keducacontrol" );
	config->writeEntry("Splitter_size", split->sizes() );
	recentFiles->saveEntries(config);
	config->sync();
}

/** Close the window */
bool kcontroldoc::queryClose ()
{
	this->configWrite();
	return( TRUE );
}

/** Add question */
void kcontroldoc::slotAdd()
{
	QPixmap image0( ( const char** ) image0_data );

	kcontroladdedit edit;
	edit.init( KEDUCA, false );
	if( !edit.exec() ) return;

	list_answer->insertItem( image0, KEDUCA->getQuestion( FileRead::QF_text ) );
	list_answer->setCurrentItem( list_answer->count()-1 );
	slotPreview( list_answer->item(list_answer->currentItem()) );
	if( KMessageBox::questionYesNo(this, i18n("Do you want to continue adding questions?")) == KMessageBox::Yes )
		slotAdd();
}

/** Edit question */
void kcontroldoc::slotEdit()
{
	if( list_answer->currentItem() == -1 ) return;

	QPixmap image0( ( const char** ) image0_data );

	kcontroladdedit edit;
	edit.init( KEDUCA, true );
	if( edit.exec() )
		{
			list_answer->changeItem( image0, KEDUCA->getQuestion( FileRead::QF_text ), list_answer->currentItem() );
			slotPreview( list_answer->item(list_answer->currentItem()) );
		}
}

/** Edit question */
void kcontroldoc::slotRemove()
{
	if( list_answer->currentItem() == -1 ) return;
	KEDUCA->recordDelete();
	list_answer->removeItem( list_answer->currentItem() );
}

/** Up record */
void kcontroldoc::slotUp()
{
	int current = list_answer->currentItem();

	if( current < 1 ) return;
	QPixmap image0( ( const char** ) image0_data );

	KEDUCA->recordSwap( true );
	QString tmpString = list_answer->text( current-1 );
	list_answer->changeItem( image0, list_answer->text( current ), current-1 );
	list_answer->changeItem( image0, tmpString, current );
	list_answer->setCurrentItem( current-1 );
}

/** Down record */
void kcontroldoc::slotDown()
{
	int current = list_answer->currentItem();

	if( current == -1 || current == (signed)(list_answer->count()-1) ) return;
	QPixmap image0( ( const char** ) image0_data );

	KEDUCA->recordSwap( true );
	QString tmpString = list_answer->text( current+1 );
	list_answer->changeItem( image0, list_answer->text( current ), current+1 );
	list_answer->changeItem( image0, tmpString, current );
	list_answer->setCurrentItem( current+1 );
}

/** Save file */
void kcontroldoc::slotFileSave()
{
	if( !isOpenFile )	{ slotFileSaveAs(); return; }

	if( checkSave() ) KEDUCA->saveFile();
}

/** Save As... */
void kcontroldoc::slotFileSaveAs()
{
	if( !checkSave() ) return;
  KURL url = KFileDialog::getSaveURL( QString::null, "*.edu|Educa "+i18n("file")+" (*.edu)", 0,  i18n("Open Educa file") );

  if( !url.isEmpty() )
		KEDUCA->saveFile( url );
}

/** Print file */
void kcontroldoc::slotFilePrint()
{
  QPrinter *printer = new QPrinter();

  if(printer->setup(this))
	{
    QPaintDeviceMetrics metrics(printer);
    QPainter p;

    const int margin=20;
    int yPos=0;
    QString text;

    p.begin(printer);
    p.setFont( QFont(font().family(), 12, QFont::Bold) );
    QFontMetrics fm = p.fontMetrics();

		KEDUCA->recordFirst();
		while(!KEDUCA->recordEOF())
		{
			p.drawText( 10, yPos+margin,  metrics.width(), fm.lineSpacing(),
									ExpandTabs | DontClip, KEDUCA->getQuestion(FileRead::QF_text) );
	    yPos += fm.lineSpacing();
	
	    p.drawLine(10, yPos+margin, metrics.width(), yPos+margin);
	    yPos += 2*fm.lineSpacing();
	
			KEDUCA->recordNext();
		}

		p.end();
  }

	delete printer;

}

/** Header info */
void kcontroldoc::slotHeader()
{
	kcontrolheader info_doc(KEDUCA);
	info_doc.exec();
}

/** Check if the current document can save */
bool kcontroldoc::checkSave()
{
	if( KEDUCA->getHeader("title").isEmpty() 		||
			KEDUCA->getHeader("category").isEmpty() ||
			KEDUCA->getHeader("type").isEmpty() 		||
			KEDUCA->getHeader("level").isEmpty()		||
			KEDUCA->getHeader("language").isEmpty() )
	{
	KMessageBox::sorry(this, i18n("I cannot save the file.\n\nYou must to fill the Document Info\n(Only description is necessary)"));
	return false;
  }

	if( list_answer->count() < 1 )
		{
		KMessageBox::sorry(this, i18n("I cannot save the file.\n\nYou must to insert a question."));
		return false;
		}

	return true;
}

/** Toggle toolbar */
void kcontroldoc::slotToggleToolBar()
{
	if(toolBar()->isVisible())
		toolBar()->hide();
		else
		toolBar()->show();
}

/** Configure keys */
void kcontroldoc::slotConfigureKeys()
{
	KKeyDialog::configureKeys( actionCollection(), xmlFile() );
}

/** Configure toolbar */
void kcontroldoc::slotConfigureToolbar()
{
	KEditToolbar edit( guiFactory(), this );
	if( edit.exec() )
	  createGUI( "keducacontrolui.rc" );
}
